package com.unytech.project.web.interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.unytech.project.annotation.ActionLabel;
import com.unytech.project.annotation.ActionMethodLabel;
import com.unytech.project.annotation.enumerate.InterceptLevel;
import com.unytech.project.annotation.enumerate.LogRecordLevel;
import com.unytech.project.common.Globals;
import com.unytech.project.common.enumerate.YesorNo;
import com.unytech.project.entity.security.OperateRecord;
import com.unytech.project.entity.system.Permission;
import com.unytech.project.service.security.OperateRecordService;
import com.unytech.project.utils.StringUtil;
import com.unytech.project.utils.SystemParams;
import com.unytech.project.web.action.ActionResult;

public class OperateRecordInterceptor extends AbstractInterceptor{
	final private Log logger = LogFactory.getLog(getClass());	
	@Resource private OperateRecordService operateRecordService;
	@Resource private SystemParams systemParams;
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		logger.info("-----进入日志拦截器-----");
		
		if (systemParams.getLogintercept().equals(YesorNo.NO.toString().toLowerCase())) {
			logger.info("日志拦截器：系统禁用日志记录功能");
			return invocation.invoke();
		}
		ActionContext act = invocation.getInvocationContext();		
		ActionProxy ap = invocation.getProxy();
		
		Method method = ap.getAction().getClass().getMethod(ap.getMethod(), null);
		
		if (method != null) {
			ActionMethodLabel aml = method.getAnnotation(ActionMethodLabel.class);
			
			//检测是否存在方法标签
			if (aml == null) {
				logger.info("日志拦截器：未定义此方法的拦截级别，将不对此请求进行日志拦截:"+ap.getMethod());
				return invocation.invoke();
			}
			
			//如果是公共方法就不进行拦截
			if (aml.intercept().equals(InterceptLevel.PUBLIC) || aml.intercept().equals(InterceptLevel.INITSYSTEM)) {
				logger.info("日志拦截器：请求的为公共方法，将不对此请求进行日志拦截:"+ap.getMethod());
				return invocation.invoke();
			}
			
			//一级日志拦截级别
			if (aml.logintercept().equals(LogRecordLevel.FORCE)) {
				logger.info("日志拦截器：一级日志拦截级别，将对此请求进行日志拦截:"+ap.getMethod());
				return dointercept(invocation, aml);
			}

			//二级义日志拦截级别，系统启用日志记录功能
			if (aml.logintercept().equals(LogRecordLevel.CUSTOM) && systemParams.getLogintercept().equals(YesorNo.YES.toString())) {
				logger.info("日志拦截器：二级义日志拦截级别，系统启用日志记录功能，将对此请求进行日志拦截:"+ap.getMethod());
				return dointercept(invocation, aml);
			}
			
			//二级义日志拦截级别，系统禁用日志记录功能
			if (aml.logintercept().equals(LogRecordLevel.CUSTOM) && systemParams.getLogintercept().equals(YesorNo.NO.toString())) {
				logger.info("日志拦截器：二级义日志拦截级别，系统禁用日志记录功能，将不对此请求进行日志拦截:"+ap.getMethod());
				return invocation.invoke();
			}
		}
		else
		{
			act.getSession().put(Globals.SESSION_MESSAGE_KEY, "对不起，没有找到此操作对应的方法！");
			return ActionResult.MESSAGE_VIEW;
		}
		act.getSession().put(Globals.SESSION_MESSAGE_KEY, "未知的请求！");
		return ActionResult.MESSAGE_VIEW;	
	}
	
	private String dointercept(ActionInvocation invocation, ActionMethodLabel aml) throws Exception {
		ActionProxy ap = invocation.getProxy();
		
		StringBuilder message = new StringBuilder();
		message.append(ap.getNamespace()).append("/").append(invocation.getProxy().getActionName());
		
		Date startdate = new Date();
		long startTime = System.currentTimeMillis();
		String result = null;
		long endTime = 0;
		long executionTime = 0;
		
		result = invocation.invoke();
		
		endTime = System.currentTimeMillis();
		executionTime = endTime - startTime;

		OperateRecord operaterecord = new OperateRecord();
		operaterecord.setRecorduri(message.toString());
		
		ActionLabel ab = ap.getAction().getClass().getAnnotation(ActionLabel.class);  //取得模块说明
		if (ab != null && ab.module() != null) {	
			operaterecord.setRecordmodule(ab.module());
		}
		//取得初始化系统时在全局变量中写入的系统全部权限信息
		Map app = invocation.getInvocationContext().getApplication();
		operaterecord.setOperatechain(StringUtil.analyRUI((List<Permission>) app.get(Globals.CONTEXT_ALLPERMISSIONS_KEY), message.toString()));
		operaterecord.setOperateaction(aml.methodnote());
		operaterecord.setStarttime(startdate);
	    operaterecord.setEndtime(new Date());
	    operaterecord.setElapsedtime((int) executionTime);
	    
	    /**操作记录写入数据库*/
	    try {
	    	operateRecordService.save(operaterecord);
	    } catch (Exception ee) {
	    	logger.info(ee.getMessage());
			logger.error(ee, ee);
	    	throw ee;
	    } 
	    
	    //生成操作时间
	    message.append("-->Start：").append(startdate).append("-->Took：").append(executionTime).append("ms");
	    logger.info(message.toString());
	    
		return result;
	}
}
